﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Threading.Tasks;
using Bing.Maps;
using LocationTrackingSample;
using MenusHunter.WinRT.Common;
using MenusHunter.WinRT.Core.Models;
using MenusHunter.WinRT.Core.Services.Restaurant;
using MenusHunter.WinRT.Core.ViewModels;
using MenusHunter.WinRT.Helpers;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace MenusHunter.WinRT.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MapView : MenusHunter.WinRT.Common.LayoutAwarePage
    {
        private readonly Geolocator _geoLocator;
        private readonly LocationIcon _locationIcon;
        private ViewMapPageViewModel _viewModel;
        private bool _foodPanelIsShowing = false;
        public MapView()
        {
            this.InitializeComponent();
            _viewModel = DataContext as ViewMapPageViewModel;
            _geoLocator = new Geolocator();
            _locationIcon = new LocationIcon();
            // Add the location icon to map layer so that we can position it.
            MainBingMap.Children.Add(_locationIcon);
            _geoLocator.PositionChanged += geoLocator_PositionChanged;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        private void DisplayPosition(object sender, PositionChangedEventArgs args)
        {
            Location location = new Location(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
            MapLayer.SetPosition(_locationIcon, location);
            MainBingMap.SetView(location, 16.0f);
        }

        private async void geoLocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
#if DEBUG
            Debug.WriteLine(args.Position.Coordinate.Latitude);
#endif


            Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                () => DisplayPosition(sender, args));
            LoadRestaurantAround(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            _geoLocator.PositionChanged -= geoLocator_PositionChanged;
        }


        private void MainBingMap_ViewChanged(object sender, ViewChangedEventArgs e)
        {
#if DEBUG
            Debug.WriteLine("view changed...");

#endif
        }

        private void LoadRestaurantAround(double lat, double lon)
        {
             Dispatcher.RunAsync(CoreDispatcherPriority.Normal,async () =>
                                      {
                                          if (_viewModel != null)
                                          {
                                              var result = await _viewModel.GetListRestaurantsAround(lat, lon, 0, 20, 2);
                                              DisplayRestaurant(result);
                                          }
                                      });
        }

        private void DisplayRestaurant(ObservableCollection<Restaurant> result)
        {
            foreach (var restaurant in result)
            {
                var image = new Image
                                {
                                    Source = new BitmapImage(new Uri(BaseUri, "/Assets/Restaurant.png")),
                                    Height = 37,
                                    Width = 32,
                                    Tag = restaurant
                                };


                MapLayer.SetPosition(image, new Location(restaurant.Latitude, restaurant.Longtitude));
                MapLayer.SetPositionAnchor(image, new Windows.Foundation.Point(16, 37));
                image.Tapped += ImageOnTapped;
                MainBingMap.Children.Add(image);
            }
        }

        private async void ImageOnTapped(object sender, TappedRoutedEventArgs tappedRoutedEventArgs)
        {
            var image = sender as Image;
            if (image != null)
            {
                var restaurant = (Restaurant) image.Tag;
                await _viewModel.GetFoodsForRestaurant(restaurant.Id);
               if(!_foodPanelIsShowing)
               {
                   _foodPanelIsShowing = true;
                   FoodsListIn.Begin();
               }
            }
        }

        private void HideFoodsPanelButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            FoodsListOut.Begin();
            _foodPanelIsShowing = false;
        }
    }
}